package com.sun.plugin;

import com.sun.source.DynamicDataSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * @author lk
 * @version 1.0.0
 * @Description 自定义拦截器
 * @createTime 2025/9/18 18:05
 */
@Intercepts({
        @Signature(type = Executor.class,method = "update",args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class,method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class DynamicDataSourcePlugin implements Interceptor {

    // 拦截的方法
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("拦截器执行：" + invocation.getTarget());
        // 目标对象
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        // 读方法
        if(ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
            System.out.println("切换到读数据源：");
            DynamicDataSource.setDataSource("R");
        }else {
            //修改当前线程要选择的数据源的key
            System.out.println("切换到写数据源：");
            DynamicDataSource.setDataSource("w");
        }
        // 执行目标方法
        return invocation.proceed();
    }

    // 返回拦截器的代理对象
    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    // 设置一些属性
    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
